<template>
  <div class="modal-from">
    <a-modal
      :form="form"
      :bodyStyle="{ padding: '0 24px' }"
      title="新增产品物料"
      :width="1000"
      style="top: 50px"
      :visible="visible"

      @ok="submit"
      @cancel="handleCancel"
    >
      <div class="table-page-search-wrapper">
        <a-form :form="form" layout="inline" ref="table">
          <a-row :gutter="24" style="margin: 10px; padding: 10px">
            <!--上面-->
            <a-col>
              <a-row class="rowStyle" :gutter="24">
                <a-col :span="6">
                  <a-form-item label="产品编码">
                    <a-input
                      :disabled="true"
                      placeholder="本项自动生成"
                      v-decorator="[
                        'code', // input 的 name
                      ]"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="产品名称">
                    <a-input
                      placeholder="请输入"
                      v-decorator="[
                        'name',
                        { rules: [{ required: true, message: '请输入！' }] }, // input 的 name
                      ]"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="打印名称">
                    <a-input
                      placeholder="请输入"
                      v-decorator="[
                        'printName',
                        { rules: [{ required: true, message: '请输入！' }] }, // input 的 name
                      ]"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="产品类别">
                    <a-tree-select
                      allowClear
                      v-decorator="['prdtTypeId', { rules: [{ required: true, message: '请输入！' }] }]" 
                      :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
                      :treeData="treeData"
                      placeholder="请选择类别"
                      :replaceFields="replaceFields"
                    >
                      <span slot="title" slot-scope="{ id }">{{ id }}</span>
                    </a-tree-select>
                  </a-form-item></a-col
                >
              </a-row>
            </a-col>
            <a-col>
              <a-row :gutter="24" class="rowStyle">
                <a-col :span="6">
                  <a-form-item label="产品类型">
                    <a-select  
                      v-decorator="[
                        'typeId',
                        { rules: [{ required: true, message: '请输入！' }] }, // input 的 name
                      ]" 
                    > 
                      <a-select-option :value="0">
                        <div>药品</div>
                      </a-select-option>
                      <a-select-option :value="1">
                        <div>物品</div>
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="剂型">
                    <a-input
                      placeholder="请输入"
                      v-decorator="[
                        'formulations', // input 的 name
                      ]"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="是否赠送">
                    <a-select 
                      @change="handleChange"
                      v-decorator="[
                        'isFree', // input 的 name
                      ]"
                    >
                      <a-select-option
                        v-for="item in is_free"
                        :key="item.id"
                        :isdisabled="item.label"
                        :value="item.label"
                      >
                        <div>{{ item.value }}</div>
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="保值期(天)">
                    <a-input-number
                      :min="0"
                      :max="365"
                      placeholder="请输入"
                      v-decorator="[
                        'expirationDate', // input 的 name
                      ]"
                    ></a-input-number> 
                  </a-form-item>
                </a-col>
              </a-row>
            </a-col>
            <a-col>
              <a-row :gutter="24">
                <a-col :span="6">
                  <a-form-item label="是否折扣">
                    <!--做下拉-->
                    <a-select 
                      @change="handleChange"
                      v-decorator="[
                        'isAllowDisc', // input 的 name
                      ]"
                    >
                      <a-select-option
                        v-for="item in is_allow_disc"
                        :key="item.id"
                        :isdisabled="item.label"
                        :value="item.label"
                      >
                        <div>{{ item.value }}</div>
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="出库方式">
                    <a-select 
                      @change="handleChange"
                      v-decorator="[
                        'outMode',
                        { rules: [{ required: true, message: '请输入！' }] }, // input 的 name
                      ]"
                    >
                      <a-select-option
                        v-for="item in out_mode"
                        :key="item.id"
                        :isdisabled="item.label"
                        :value="item.label"
                      >
                        <div>{{ item.value }}</div>
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="库存上限">
                    <a-input-number
                      :step="1"
                      :min="0"
                      :max="10000000"
                      placeholder="请输入"
                      v-decorator="[
                        'upperLimit', // input 的 name
                      ]"
                    ></a-input-number>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="库存下限">
                    <a-input-number
                      placeholder="请输入"
                      v-decorator="[
                        'downLimit', // input 的 name
                      ]"
                      :step="1"
                      :min="0"
                      :max="10000000"
                    ></a-input-number> </a-form-item
                ></a-col>
              </a-row>
            </a-col>
            <a-col>
              <a-row :gutter="24">
                <a-col :span="6">
                  <a-form-item label="是否禁用">
                    <!--做下拉-->
                    <a-select 
                      @change="handleChange"
                      v-decorator="[
                        'isDisabled', // input 的 name
                      ]"
                    >
                      <a-select-option
                        v-for="item in is_disabled"
                        :key="item.id"
                        :isdisabled="item.label"
                        :value="item.label"
                      >
                        <div>{{ item.value }}</div>
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="批准文号">
                    <a-input
                      placeholder="请输入"
                      v-decorator="[
                        'approvalNumber', // input 的 name
                      ]"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="默认仓位">
                    <a-input
                      placeholder="请输入"
                      v-decorator="[
                        'defaultPosition', // input 的 name
                      ]"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="业绩科室">
                    <a-select 
                      @change="handleChange"
                      v-decorator="[
                        'achieveDept',
                        { rules: [{ required: true, message: '请输入！' }] }, // input 的 name
                      ]"
                    >
                      <a-select-option v-for="item in deptlist" :key="item.id" :value="item.label">
                        <div>{{ item.name }}</div>
                      </a-select-option>
                    </a-select>
                  </a-form-item></a-col
                >
              </a-row>
            </a-col>
            <a-col>
              <a-row :gutter="24">
                <a-col :span="6">
                  <a-form-item label="注册文号">
                    <a-input
                      placeholder="请输入"
                      v-decorator="[
                        'registrationSymbol', // input 的 name
                      ]"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="产地">
                    <a-input
                      placeholder="请输入"
                      v-decorator="[
                        'productionPlace', // input 的 name
                      ]"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="生产厂家">
                    <a-input
                      placeholder="请输入"
                      v-decorator="[
                        'factoryName', // input 的 name
                      ]"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6"> 
                  <a-form-item label="耗材名称"> 
                    <a-select 
                      v-decorator="[
                        'consumableName',
                        { rules: [{ required: true, message: '请选择' }] }, // input 的 name
                      ]"
                    >
                      <a-select-option v-for="(item, index) in amtTypeList" :key="index" :value="item.id">
                        <div>{{ item.name }}</div>
                      </a-select-option>
                    </a-select> 
                    
                  </a-form-item>
                </a-col>
              </a-row>
            </a-col>
            <a-col>
              <a-row :gutter="24">
                <a-col :span="12">
                  <a-form-item label="备注">
                    <a-textarea
                      placeholder="请输入"
                      v-decorator="[
                        'remark', // input 的 name
                      ]"
                    ></a-textarea>
                  </a-form-item>
                </a-col>
              
                <a-col :span="12">
                  <a-form-item>
                    <a-checkbox v-decorator="['isDeal', { valuePropName: 'checked' }]">核算成交</a-checkbox>
                    <a-checkbox v-decorator="['isAchieve', { valuePropName: 'checked' }]">核算业绩</a-checkbox>
                    <a-checkbox v-decorator="['isSell', { valuePropName: 'checked' }]">是否销售</a-checkbox>
                  </a-form-item>
                </a-col>
                 
                
              </a-row>
            </a-col>
            <a-col :span="24" style="margin: 10px 0">
              <div>
                <span></span>
              </div>
            </a-col>
            <a-col :span="24">
              <uniTable ref="uniTableRef" :formData="row_record.definitionList" :formId="row_record.id"></uniTable>
              <!-- <super-table
                ls_props_columns="projectManage_table"
                :scroll="{ x: 1000 }"
                ref="table"
                :pageSize="10"
                :columns="columns"
                :data="loadData"
                :rowKey="(record) => record.id"
              >
                <template slot="action" slot-scope="text, record">
                  <div class="g-flex g-y-center">
                    <a-button type="link" @click="editProject(record)">编辑</a-button>
                  </div>
                </template>
              </super-table> -->
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { getDeptList, getAmtTypeList } from '@/api/modular/main/customer/customerScene' 
import { addProduct, getProduct, editProdut } from '@/api/bd/product'
import { getItemDetailById } from '@/api/bd/product'
import { SuperTable } from '@/components'
import uniTable from './compont/uniTable.vue'
export default {
  props: {
    modal_type: {
      type: String,
      default: 'add',
    },
    row_record: {
      type: Object,
      default: () => {},
    },
  },

  components: {
    SuperTable,
    uniTable,
  },
  data() {
    return {
      amtTypeList:[], // 耗材名称
      replaceFields: {
        title: 'name',
      },

      is_free: [
        {
          id: 0,
          value: '否',
          label: '0',
        },
        {
          id: 1,
          value: '是',
          label: '1',
        },
      ],
      out_mode: [
        {
          id: 0,
          value: '先进先出',
          label: '0',
        },
        {
          id: 1,
          value: '过期先出',
          label: '1',
        },
        {
          id: 2,
          value: '后进先出',
          label: '2',
        },
        {
          id: 3,
          value: '指定批次',
          label: '3',
        },
      ],
      is_allow_disc: [
        {
          id: 0,
          value: '不允许',
          label: '0',
        },
        {
          id: 1,
          value: '允许',
          label: '1',
        },
      ],
      is_disabled: [
        { id: 0, value: '是', label: '1' },
        {
          id: 1,
          value: '否',
          label: '0',
        },
      ],
      treeData: [],
      form: this.$form.createForm(this),
      queryParam: {
        searchValue: '',
        pageNum: 1, //第几页
        pageSize: 10, //每页中显示数据的条数
        id: undefined,
      },
      customer_response: {},
      pagination: {
        current: 1, //当前页
        pageSize: 20, //当前页数
        total: 0, //总条数
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30'], //这里注意只能是字符串，不能是数字
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
      // 表头
      columns: [
        { title: '计量单位', dataIndex: 'code', width: 120, fixed: 'left' },
        { title: '单位进制', dataIndex: '1', width: 120 },
        { title: '是否基本单位', dataIndex: '2', width: 120 },
        { title: '规格', dataIndex: '3', width: 120 },
        { title: '单位单价', dataIndex: 'name', width: 120, scopedSlots: { customRender: 'name' }, ellipsis: true },
        { title: '操作', scopedSlots: { customRender: 'action' }, fixed: 'right', width: 100 },
      ],
      loadData: (parameter) => {
        return getItemDetailById(Object.assign(parameter, this.queryParam)).then((res) => {
          console.log('右边表格', res)
          return res
        })
      },
      value: [],
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 },
      },
      visible: false,
 
      customerTableLoading: false,
      pagination: {
        current: 1, //当前页
        pageSize: 10, //当前页数
        total: 0, //总条数
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30'], //这里注意只能是字符串，不能是数字
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
      customerDataTable: [],
      deptlist: [],
      checked: true,
    }
  },
  created(){
    // 耗材下拉框
    getAmtTypeList().then((res) => {
      console.log('费用列表', res)
      this.amtTypeList = res
    })
  },
  mounted() {
    this.getDept()
    getProduct().then((res) => {
      this.treeData = res.data
      console.log(res, 'addproject')
    })
  },
  methods: { 
    changeDeal(val) {
      console.log(val, this.checked)
      this.checked = !this.checked
    },
    changeSell(val) {
      console.log(val)
    },
    changeAchieve(val) {
      console.log(val)
    },
    getDept() {
      getDeptList().then((res) => {
        res.data.forEach((item) => {
          item.label = item.id
        })
        this.deptlist = res.data
      })
    },
    // 初始化方法
    add() {
      const that = this
      this.visible = true
      console.log('111', this.modal_type, this.row_record)
      this.$nextTick(() => {
        if (this.modal_type === 'add') {
          //状态为新增，不会存在id
          console.log('新增')
          this.form.resetFields() //重置表单
          this.$refs.uniTableRef.data = [
            {
              unitMeasurement:'件',
              systemRatio: '1',
              spec: '',
              price: 0,
              isBasicUnit:1
            }
          ]
          return
        }
        if (this.modal_type === 'edit' && this.row_record.id) {
          //this.row_record是父组件过来的行数据，如果状态为修改，必须状态标识为edit和id同时拥有
          const record = this.row_record

          this.customer_response.custormerId = record.id 

          this.$refs.uniTableRef.data = [...record.definitionList]

         
          // 提交的时候会根据customer_response这个对象的id来判断是什么动作，这个对象的id的值只能在这里赋值          this.customer_response.isSell = this.customer_response.isSell === '1' ? true : false
          


          // this.customer_response.isAchieve = this.row_record.isAchieve == '1' ? true : false 
          // this.customer_response.isSell = this.row_record.isSell == '1' ? true : false 
          // this.customer_response.isDeal = this.row_record.isDeal == '1' ? true : false

          that.$nextTick(() => {
            setTimeout(() => {
              that.form.setFieldsValue({
                //数据回填
                isSell: Number(this.row_record.isSell) ? true : false ,
                isAchieve: Number(this.row_record.isAchieve) ? true : false,
                isDeal: Number(this.row_record.isDeal) ? true : false,
                remark: record.remark,
                // isDeal: record.isDeal,
                factoryName: record.factoryName,
                productionPlace: record.productionPlace,
                registrationSymbol: record.registrationSymbol,
                defaultPosition: record.defaultPosition,
                approvalNumber: record.approvalNumber,
                achieveDept: record.achieveDept || '',
                isDisabled: record.isDisabled,
                downLimit: record.downLimit,
                upperLimit: record.upperLimit,
                isAllowDisc: record.isAllowDisc,
                formulations: record.formulations,
                isFree: record.isFree,
                expirationDate: record.expirationDate,
                outMode: record.outMode,
                prdtTypeId: record.prdtTypeId,
                typeId: Number(record.typeId),
                code: record.code,
                name: record.name,
                printName: record.printName,
                consumableName: record.consumableName,
                // pyCode: record.pyCode,
                // maxPrice: record.maxPrice,
                // minPrice: record.minPrice,
                // doctorScore: record.doctorScore,
                // modifier: record.modifier,
                // nurseScore: record.nurseScore,
                // operateName: record.operateName,
                // price: record.price,
                // twoDeptId: null,
              })
            },100)
            
          })
        }
      })
    },
    adds() {
      const form = this.form.getFieldsValue()
      console.log(form, '表单数据')
    },
    /**
     提交表单
     * */
    submit() {
      const {
        form: { validateFields },
      } = this
     console.log(this.$refs.uniTableRef.data)
      validateFields((errors, values) => {
      
        console.log(this.customer_response.custormerId, '11111')
        if (errors) {
          console.log('表单检验未通过111', errors, values)

          return
        }
        if(this.$refs.uniTableRef.data.length <= 0){
          this.$message.error('请先新增一条产品数据')
          return
        }
        let boolUni = this.$refs.uniTableRef.data.find(item => {
          return item.unitMeasurement == '' || item.systemRatio == '' || item.spec == ''
        })
          
        let setData = this.$refs.uniTableRef.data.map(item => {
          item.unitMeasurement == '' ? item.unitMeasurementBorder = true:item.unitMeasurementBorder = false
          item.systemRatio == '' ? item.systemRatioBorder = true : item.systemRatioBorder = false
          item.spec == '' ? item.specBorder = true : item.specBorder = false 
          return item
        }) 
        this.$refs.uniTableRef.data = setData
       
       
        
         
        if(boolUni != undefined){
          this.$message.error('产品信息必填项不能为空！')
          return
        }
        let isBasciUnit = this.$refs.uniTableRef.data.find(item=>{
          return item.isBasicUnit == 1
        })
        if (this.customer_response.custormerId) { 
          values.id = this.customer_response.custormerId
          console.log('表单检验通过222', values)
          values.isDeal =  values.isDeal === true ? '1' : '0'
          values.isAchieve = values.isAchieve === true ? '1' : '0'
          values.isSell = values.isSell === true ? '1' : '0'
          values.basicUnit = '-'
          values.spec = '-'
          values.pyCode = 'asda'
          values.definitionList = this.$refs.uniTableRef.data
          values.basicUnit = isBasciUnit.unitMeasurement
          editProdut(values).then((res) => {
                   if (res.code && res.code.toString() !== '200') {
              return this.$message.error(res.msg || res.message)
            } else {
            this.customer_response.custormerId = ''
            this.$emit('search')}
            console.log(res)
          })
   
          this.visible = false
        } else {
          console.log('表单检验通过222', values)
          values.isDeal =  values.isDeal === true ? '1' : '0'
          values.isAchieve = values.isAchieve === true ? '1' : '0'
          values.isSell = values.isSell === true ? '1' : '0'
          values.basicUnit = '-'
          values.spec = '-'
          values.definitionList = this.$refs.uniTableRef.data
          values.basicUnit = isBasciUnit.unitMeasurement
           
          addProduct(values).then((res) => {
            res.code === 200
              ? this.$message.success(res.msg || res.message)
              : this.$message.error(res.msg || res.message)
            this.$emit('search')
          })

          this.visible = false
        }
      })
    },
    /**
     分页动作监听
     * */
    handleTableChange(pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.queryParam.pageNum = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      this.getList()
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
      this.customer_response.custormerId = ''
    },
    handleChange(is_disabled) {
      console.log(is_disabled)
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .ant-card-head-title {
  font-weight: bold;
}

/deep/ .ant-page-header-heading-title {
  font-weight: normal;
  font-size: 16px;
}

/deep/ .ant-card-body {
  padding: 24px 12px 0 !important;
}

/deep/ .ant-form-item-control-wrapper {
  width: 100%;
}
/deep/ .ant-form-item-control {
  width: 100%;
}
/deep/ .ant-row {
  margin: 10 15px;
}
/deep/ .table-page-search-wrapper .ant-form-inline .ant-form-item > .ant-form-item-label{
  width: 90px;
}
/deep/ .table-page-search-wrapper .ant-form-inline .ant-form-item .ant-form-item-control-wrapper{
  width: calc(100% - 90px);
}
.ant-input-number{
  width: 100%;
}
</style>